package com.demo.helper;

import com.demo.log.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Set;

@Component
public class EnvHelper {

  private static final Logger LOG = Logger.get(EnvHelper.class);

  private static final String PRD_PREFIX = "prd";
  private static final String PRE_PREFIX = "pre";

  private boolean test;

  @Value("${spring.profiles.active}")
  private String env;

  @Value("#{'${allow.send.phones:}'.split('\\|')}")
  private Set<String> phoneWhitelist;
  @Value("#{'${allow.send.email:}'.split('\\|')}")
  private Set<String> emailWhitelist;


  @PostConstruct
  public void init() {
    test = !env.startsWith(PRD_PREFIX) && !env.startsWith(PRE_PREFIX);
  }

  public boolean isTest() {
    return test;
  }

  public boolean checkSendEmailCondition(String email) {
    return checkCondition(email, emailWhitelist);
  }

  public boolean checkSendSmsCondition(String phone) {
    return checkCondition(phone, phoneWhitelist);
  }

  private boolean checkCondition(String receiver, Set<String> whitelist) {

    if (isTest()) {
      // 测试环境必须白名单才能发送
//            if (whitelist.contains(receiver)) {
//                return true;
//            }
      return true;
    }
//        else {
//
//            // 生产环境白名单必须配置 *
//            if (whitelist.contains("*")) {
//                return true;
//            }
//        }
//        if(LOG.isWarnEnabled()){
//            LOG.warn(format("发送消息-测试环境不在白名单或生产环境配置错误", kv("env", env), kv("receiver", encryptPhoneOrEmail(receiver))));
//        }
    return true;
  }


  public String getEnv() {
    return env;
  }


}
